package com.example.week2_try2;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

import java.security.PublicKey;

public class MainActivity4 extends AppCompatActivity {

    public static final String TAG= "Exchange";

    EditText dollar1,euro1,won1;
    float dollar2,euro2,won2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main4);
        Intent intent=getIntent();
        dollar1=findViewById(R.id.dollar_rate);
        euro1=findViewById(R.id.euro_rate);
        won1=findViewById(R.id.won_rate);

        dollar2=intent.getFloatExtra("dollar_rate",0.0f);
        euro2=intent.getFloatExtra("euro_rate",0.0f);
        won2=intent.getFloatExtra("won_rate",0.0f);

        dollar1.setText(String.valueOf(dollar2));
        euro1.setText(String.valueOf(euro2));
        won1.setText(String.valueOf(won2));

        Log.i(TAG,"onCreate:dollar_rate="+dollar2);
        Log.i(TAG,"onCreate:euro_rate="+euro2);
        Log.i(TAG,"onCreate:won_rate="+won2);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mymenu,menu);
        return true;
    }

    public void saveChange(View btn){

        dollar1=findViewById(R.id.dollar_rate);
        euro1=findViewById(R.id.euro_rate);
        won1=findViewById(R.id.won_rate);

        float newDollar=Float.parseFloat(dollar1.getText().toString());
        float newEuro=Float.parseFloat(euro1.getText().toString());
        float newWon=Float.parseFloat(won1.getText().toString());

        savetoSP(newDollar, newEuro, newWon);

        Intent second=getIntent();
        //this当前activity对象
        //putExtra--传递参数
        second.putExtra("dollar_rate",newDollar);
        second.putExtra("euro_rate",newEuro);
        second.putExtra("wonr_rate",newWon);

        Log.i(TAG,"saveChange:dollar_rate="+newDollar);
        Log.i(TAG,"saveChange:euro_rate="+newEuro);
        Log.i(TAG,"saveChange:won_rate="+newWon);
        setResult(2,second);
        //startActivity(second);
        finish();
    }

    private void savetoSP(float newDollar, float newEuro, float newWon) {
        SharedPreferences sp=getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);

        SharedPreferences.Editor editor= sp.edit();
        editor.putFloat("dollar_rate", newDollar);
        editor.putFloat("euro_rate", newEuro);
        editor.putFloat("wonr_rate", newWon);

        editor.apply();
    }
}